package com.roads.site.service.impl;

import com.roads.common.constant.ResultConstants;
import com.roads.common.constant.UserConstants;
import com.roads.common.core.domain.AjaxResult;
import com.roads.common.core.domain.ExcelResult;
import com.roads.common.utils.DateUtils;
import com.roads.common.utils.StringUtils;
import com.roads.site.domain.SiteLabourTeam;
import com.roads.site.mapper.SiteLabourTeamMapper;
import com.roads.site.service.ISiteLabourTeamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 施工班组Service业务层处理
 * 
 * @author nhp
 * @date 2022-10-25
 */
@Service
public class SiteLabourTeamServiceImpl implements ISiteLabourTeamService {

    @Autowired
    private SiteLabourTeamMapper mapper;

    /**
     * 根据主键ID查询详情
     * 
     * @param id 施工班组主键
     * @return 施工班组
     */
    @Override
    public SiteLabourTeam getModelById(Integer id) {
        return mapper.getModelById(id);
    }

    /**
     * 使用数量
     *
     * @param id id
     * @return 数量
     */
    @Override
    public int useCount(Integer id) {
        return mapper.useCount(id);
    }

    /**
     * 查询列表
     * 
     * @param model 施工班组
     * @return 施工班组
     */
    @Override
    public List<SiteLabourTeam> selectModelList(SiteLabourTeam model) {
        return mapper.selectModelList(model);
    }

    /**
     * 施工班组下拉框
     *
     * @param institutionCode 标段编号
     * @return 结果
     */
    @Override
    public List<SiteLabourTeam> dropDownList(String institutionCode) {
        return mapper.dropDownList(institutionCode);
    }

    /**
     * 校验施工班组名称是否唯一
     *
     * @param model 施工班组
     * @return 结果
     */
    @Override
    public String checkNameUnique(SiteLabourTeam model) {
        Integer teamId = StringUtils.isNull(model.getTeamId()) ? -1 : model.getTeamId();
        SiteLabourTeam info = mapper.checkNameUnique(model.getInstitutionCode(), model.getTeamName());
        if (StringUtils.isNotNull(info) && !info.getTeamId().equals(teamId)) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 新增
     * 
     * @param model 施工班组
     * @return 结果
     */
    @Override
    public int insert(SiteLabourTeam model) {
        model.setCreateTime(DateUtils.getNowDate());
        // 设置序号（排序）
        int maxSerialNumber = mapper.getMaxSerialNumber(model.getInstitutionCode());
        maxSerialNumber++;
        model.setOrderNum(maxSerialNumber);
        return mapper.insert(model);
    }

    /**
     * 修改
     * 
     * @param model 施工班组
     * @return 结果
     */
    @Override
    public int update(SiteLabourTeam model) {
        model.setUpdateTime(DateUtils.getNowDate());
        return mapper.update(model);
    }

    /**
     * 批量删除
     * 
     * @param ids 主键集合
     * @return 结果
     */
    @Override
    public int deleteByIds(Integer[] ids) {
        return mapper.deleteByIds(ids);
    }

    /**
     * 删除
     * 
     * @param id 施工班组主键
     * @return 结果
     */
    @Override
    public int delete(Integer id) {
        return mapper.delete(id);
    }

    /**
     * 施工班组导入
     *
     * @param list 导入数据
     * @param updateSupport 是否覆盖更新
     * @param loginUser 登录用户
     * @param institutionCode 标段编号
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult importData(List<SiteLabourTeam> list, boolean updateSupport, String loginUser, String institutionCode) {
        AjaxResult ajaxResult = new AjaxResult();
        Date nowDate = DateUtils.getNowDate();
        // excel导入结果集合
        List<ExcelResult> excelResults = new ArrayList<>();
        // 取出该标段下的所有施工班组
        SiteLabourTeam teamSearch = new SiteLabourTeam();
        teamSearch.setInstitutionCode(institutionCode);
        // 数据库已经添加的施工班组
        List<SiteLabourTeam> dbTeamList = mapper.selectModelList(teamSearch);
        // 取出施工班组最大序列号
        int maxSerialNumber = mapper.getMaxSerialNumber(institutionCode);
        maxSerialNumber++;
        // 即将插入，更新的施工班组集合
        List<SiteLabourTeam> insertTeamList = new ArrayList<>();
        List<SiteLabourTeam> updateTeamList = new ArrayList<>();
        // excel起始行
        int index = 2;
        for (SiteLabourTeam row : list) {
            ExcelResult excelResult = new ExcelResult();
            excelResult.setRow(index);
            row.setInstitutionCode(institutionCode);
            StringBuilder content = new StringBuilder();
            String teamName = row.getTeamName();
            if (StringUtils.isEmpty(teamName)) {
                content.append("班组名称不能为空;");
                excelResult.setStatus(ResultConstants.RESULT_ERROR);
            }
            // 数据格式有问题，就不用去比对是否存在的逻辑
            if (!ResultConstants.RESULT_ERROR.equals(excelResult.getStatus())) {
                // 查看施工班组是否存在
                SiteLabourTeam team = checkIsExist(teamName, dbTeamList);
                boolean teamIsInsert = checkIsInsert(teamName, insertTeamList);
                // 如果数据库存在，并且不进行覆盖更新，则报错
                if (StringUtils.isNotNull(team) && !updateSupport) {
                    content.append("班组名称已存在;");
                    excelResult.setStatus(ResultConstants.RESULT_ERROR);
                } else if (StringUtils.isNotNull(team) && updateSupport) {
                    content.append("更新数据库;");
                    excelResult.setStatus(ResultConstants.RESULT_SUCCESS);
                    row.setTeamId(team.getTeamId());
                    row.setOrderNum(team.getOrderNum());
                    row.setCreateBy(team.getCreateBy());
                    row.setCreateTime(team.getCreateTime());
                    row.setUpdateBy(loginUser);
                    row.setUpdateTime(nowDate);
                    updateTeamList.add(row);
                } else if (StringUtils.isNull(team) && teamIsInsert) {
                    content.append("重复数据;");
                    excelResult.setStatus(ResultConstants.RESULT_ERROR);
                } else if (StringUtils.isNull(team) && !teamIsInsert) {
                    row.setOrderNum(maxSerialNumber);
                    row.setCreateBy(loginUser);
                    row.setCreateTime(nowDate);
                    excelResult.setStatus(ResultConstants.RESULT_SUCCESS);
                    insertTeamList.add(row);
                    maxSerialNumber++;
                }
            }
            excelResult.setContent(content.toString());
            index++;
            excelResults.add(excelResult);
        }

        boolean result = true;
        for (ExcelResult excelResult : excelResults) {
            if (ResultConstants.RESULT_ERROR.equals(excelResult.getStatus())) {
                result = false;
                break;
            }
        }
        if (result) {
            // 批量插入和更新
            if (insertTeamList.size() > 0) {
                mapper.insertBatch(insertTeamList);
            }
            if (updateTeamList.size() > 0) {
                mapper.updateBatch(updateTeamList);
            }
            ajaxResult.put(ResultConstants.RESULT_TAG_MSG, ResultConstants.RESULT_SUCCESS_MESSAGE);
            ajaxResult.put(ResultConstants.RESULT_TAG_STATUS, ResultConstants.RESULT_SUCCESS);
        } else {
            ajaxResult.put(ResultConstants.RESULT_TAG_MSG, ResultConstants.RESULT_ERROR_MESSAGE);
            ajaxResult.put(ResultConstants.RESULT_TAG_STATUS, ResultConstants.RESULT_ERROR);
        }
        ajaxResult.put(ResultConstants.RESULT_TAG_ROWS, excelResults);
        return ajaxResult;
    }

    /**
     * 检查施工班组名称是否存在
     *
     * @param name 班组名称
     * @param dbList 数据库里存放的施工班组
     * @return 结果
     */
    private SiteLabourTeam checkIsExist(String name, List<SiteLabourTeam> dbList) {
        SiteLabourTeam post = null;
        for (SiteLabourTeam temp : dbList) {
            if (name.equals(temp.getTeamName())) {
                post = temp;
                break;
            }
        }
        return post;
    }

    /**
     * 检查施工班组名称是否已经添加至insert集合
     *
     * @param name 工种名称
     * @param insertList 需要插入的施工班组
     * @return 结果
     */
    private boolean checkIsInsert(String name, List<SiteLabourTeam> insertList) {
        boolean result = false;
        for (SiteLabourTeam battalion : insertList) {
            if (name.equals(battalion.getTeamName())) {
                result = true;
                break;
            }
        }
        return result;
    }

}
